package Concurrency2.Chapter08_Pattern.fork_join;

import java.util.concurrent.RecursiveTask;

/**
 * Instruction：计算0-100的累加任务
 * 试验目的: 理解ForkJoin模式中任务的定义
 * Author：@author MaLi
 */
public class AccumulateTask extends RecursiveTask<Integer> {
    //用于判断规模: 判断是否分治的阈值
    private static final int THRESHOLD = 2;
    //累加的起始编号
    private int start;
    //累加的结束编号
    private int end;

    public AccumulateTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //阈值计算
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            //直接计算
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //分治
            int middle = (start + end) / 2;
            AccumulateTask taskA = new AccumulateTask(start, middle);
            AccumulateTask taskB = new AccumulateTask(middle + 1, end);
            taskA.fork();
            taskB.fork();
            Integer taskAResult = taskA.join();
            Integer taskBResult = taskB.join();
            sum = taskAResult + taskBResult;
        }
        return sum;
    }
}
